<template>
    <view style="display: flex;align-items: center;flex-direction: column;">
        <view class="coverImage">
            <view class="imageWrapper" v-if="articleObj.coverImage.length>0">
                <image class="image" :src="articleObj.coverImage" mode=""></image>
                <image class="delete" @click="onDeleteCoverImage"
                    src="../static/image/article_edit_icon_close_picture.png" mode=""></image>
            </view>


            <view class="upload" v-else @click="onPopupOpen">
                <image class="icon" src="../static/image/article_edit_cover_icon_add.png" mode=""></image>
                点击上传
            </view>
            <view class="text">
                封面图
            </view>
        </view>
        <view class="container">
            <view class="title">
                标题
                <textarea auto-focus="true" class="edit" auto-height="true" @input="titleChange" maxlength="100"
                    :value="articleObj.title" placeholder="请输入标题">
                </textarea>
            </view>
            <view class="line">

            </view>
            <!-- <view style="font-size: 30rpx;color: #666666;margin-top: 25rpx;margin-bottom: 25rpx;">
                内容
            </view> -->
            <view class="content">
                <view class="nodes">
                    <view class="node" v-for="(node, index) in articleObj.nodes" :key="node.id">
                        <textarea auto-focus="true" @blur="textBlur($event, index)" @input="textChange($event, node)"
                            class="text" auto-height="true" maxlength="-1" v-if="node.type == 'text'"
                            :cursor="node.cursor" :value="node.content" placeholder="请输入文章内容">
                        </textarea>

                        <image @load="imageLoad($event, node)" class="image" v-if="node.type=='image'" :src="node.url">
                        </image>

                        <view class="btn-delete" @click="deleteImage($event, node, index)" v-if="node.type=='image'">
                            删除
                        </view>
                    </view>
                </view>

                <view class="addImg" @click="selectImage">
                    <image style="width: 60rpx;height: 60rpx;" 
                        src="../static/image/article_edit_insert_icon_img.png" mode=""></image>
                    插入图片
                </view>

            </view>
        </view>
        <view class="saveBtn" @click="onSaveArticle">
            保存
        </view>

        <u-popup :show="showBottomPopup" @close="showBottomPopup=false" mode="bottom" border-radius="40">
            <view class="popupContainer">
                <view class="wrapper camera" @click="selectFromCameraAlbum('camera')">
                    <image class="icon" src="../static/image/article_frame_icon_photo.png" mode=""></image>
                    拍照上传
                </view>
                <view class="line">

                </view>
                <view class="wrapper album" @click="selectFromCameraAlbum('album')">
                    <image class="icon" src="../static/image/article_frame_icon_atlas.png" mode=""></image>
                    相册上传
                </view>
                <view class="line">

                </view>
                <view class="wrapper cancel" @click="onPopupClose">
                    取消
                </view>
            </view>
        </u-popup>
        
        <kps-image-cutter @ok="onSave" @cancel="onCancle" :url="srcImgUrl" :fixed="true" :width="cutWidth" :height="cutHeight"></kps-image-cutter>
    </view>
</template>

<script>
    import {
        mapState,
        mapMutations,
        mapActions
    } from 'vuex';
    const Config = require("@/config.js")
    const api = require("@/static/js/api.js")
    const utils = require("@/static/js/utils.js")
    import kpsImageCutter from "../components/ksp-image-cutter/ksp-image-cutter.vue";
    let that = null
    export default {
        components: {kpsImageCutter},
        data() {
            return {
                sequence: 0,
                selection: {
                    index: 0,
                    cursor: 0
                },
                
                articleId:"",
                articleObj: {
                    coverImage: "",
                    title: "",
                    nodes: [],
                },
                
                cutWidth: uni.upx2px(690),
                cutHeight: uni.upx2px(240), 
                srcImgUrl: "",
                cutedImgUrl: "",
                
                showBottomPopup: false,
            };
        },
        onLoad(options) {
            console.log("options:",options)
            that = this
        
            if (options.id&&options.id.length>0){
                that.articleId = options.id;
                console.log("create Article 0")
                that.getArticleDetail(options.id)
            }else{
                console.log("create Article 1")
                that.articleId = "";
                that.initNodes();
            }
        },

        computed: {
            ...mapState({
                hasLogin: state => state.userInfo.hasLogin,
                isAuthUserInfo: state => state.userInfo.isAuthUserInfo,
                isAuthPhone: state => state.userInfo.isAuthPhone,
                isSeller: state => state.userInfo.isSeller,
                avatarUrl: state => state.userInfo.avatarUrl,
                nickName: state => state.userInfo.nickName,
                telephone: state => state.userInfo.telephone,
                buyerId: state => state.userInfo.buyerObj.id,
            }),
        },

        methods: {
            getArticleDetail(id){
                api.getArticleDetail({
                    interfaceName: id,
                    param: {

                    }
                }).then(res => {
                    console.log(res)
                    if (res.success) {
                        that.articleObj.coverImage = res.data.cover||"";
                        that.articleObj.title = res.data.title||"";
                        console.log(JSON.parse(res.data.content))
                        
                        var list = JSON.parse(res.data.content)||[]; 
                        that.initNodes(list);
                    }
                }) 
                
            },
            
            onSaveArticle(){
                if (that.articleObj.coverImage.length<=0){
                    uni.showModal({
                        content: "封面图片未选择",
                        showCancel: false
                    });
                    return;    
                }  
                if (that.articleObj.title<=0){
                    uni.showModal({
                        content: "标题不能为空",
                        showCancel: false
                    });
                    return;    
                } 
                
                if (that.articleId.length>0){
                    api.updateArticle({
                        param: {
                            id: that.articleId,
                            content: JSON.stringify(that.articleObj.nodes),
                            cover: that.articleObj.coverImage,
                            title: that.articleObj.title,
                            status: "1",
                        }
                    }).then(res => {
                        console.log(res)
                        if (res.success) {
                            uni.navigateBack({
                                
                            })
                        }
                    }) 
                }else{
                    api.addArticle({
                        param: {
                            content: JSON.stringify(that.articleObj.nodes),
                            cover: that.articleObj.coverImage,
                            title: that.articleObj.title,
                            status: "1",
                        }
                    }).then(res => {
                        console.log(res)
                        if (res.success) {
                            uni.navigateBack({
                                
                            })
                        }
                    }) 
                }
            },
            //====Oss上传图片
            //===  https://www.cnblogs.com/fan-zha/p/11356154.html
            getOssSignature(path, callback) {
                api.getOssSignature({
                    param: {
                        dir: Config.productId+"/"+that.buyerId,
                    }
                }).then(res => {
                    console.log("getOssSignature",res)
                    if (res.success) {
                        typeof callback == 'function' && callback(path, res.data);
                    }
                })
            },
            uploadImage(path, callback) {
                function uploadConduct(path, signTmp){
                    let sign = signTmp;
                    let imageSrc = path;
                    let fileName = Config.productId+"/"+that.buyerId+'/'+"cover"+ utils.uuid()+'.png'; // 自定义上传后的文件名称
                    console.log(sign, imageSrc, fileName)
                    let uploadTask = uni.uploadFile({
                        url: sign.host,
                        filePath: imageSrc,
                        fileType: 'image',
                        name: 'file',
                        formData: {
                            'key': sign.key, //sign.key,  //fileName,
                            'AccessKeyId': sign.ak,
                            'Policy': sign.policy,         
                            //让服务端返回200,不然，默认会返回204
                            'Signature': sign.signature,
                        },
                        success: (res) => {
                            console.log('uploadImage success, res is:', res)
                            uni.showToast({
                                title: '上传成功',
                                icon: 'success',
                                duration: 1000
                            });
                            if (res.statusCode == 200){
                                var path = sign.host + fileName;
                                typeof callback == 'function' && callback(path);
                            }
                            that.$emit('imgUploaded', {
                                data: sign.host + fileName,
                                authId: that.authId
                            });
                            uni.hideLoading()
                        },
                        fail: (err) => {
                            uni.hideLoading()
                            console.log('uploadImage fail', err);
                            uni.showModal({
                                content: err.errMsg,
                                showCancel: false
                            });
                        }
                    });
                    uploadTask.onProgressUpdate((res) => {
                        console.log("上传进度" + res.progress);
                        that.progress = res.progress;
                    });
                }
                
                
                uni.showLoading({
                    title:"上传图片"
                })
                that.getOssSignature(path,(path, signTmp)=>{
                    uploadConduct(path, signTmp)
                })           
                // this.$emit('imgUploaded', {data: files.tempFilePaths[0], authId: this.authId});
            },

            //=====封面编辑
            onPopupOpen() {
                this.showBottomPopup = true;
            },
            onPopupClose() {
                this.showBottomPopup = false;
            },
            selectFromCameraAlbum(type) {
                this.showBottomPopup = false;
                uni.chooseImage({
                    count: 1,
                    sourceType: [type],
                    success: (res) => {
                        var path = res.tempFilePaths[0];
                        that.srcImgUrl = res.tempFilePaths[0];
                        // 实际项目中应上传图片到服务一起，获取url后再添加
                        // that.articleObj.coverImage = path;

                    }
                })
            },
            onDeleteCoverImage() {
                that.articleObj.coverImage = "";
            },
            
            onSave(ev) {
                var path = ev.path;
                // that.getOssSignature(path, (path, sign) => {
                //     this.uploadImage(path, sign)
                // })
                that.uploadImage(path, (url)=>{
                    that.articleObj.coverImage = url
                })
                this.srcImgUrl = "";                
            },
            onCancle() {
                // url设置为空，隐藏控件
                this.srcImgUrl = "";
            },
            //======文章编辑
            initNodes(initList) {
                var list = initList || [];
                if (Object.prototype.toString.call(list) != "[object Array]") {
                    throw new Error("数据格式不正确！")
                }
                var nodes = [];
                for (var i = 0; i < list.length; i++) {
                    var ele = list[i];
                    if (ele.type == "text") {
                        var node = {};
                        node.type = "text";
                        node.id = this.obtainSequence();
                        node.content = ele.content || "";
                        nodes.push(node);
                    } else if (ele.type == "image") {
                        var node = {};
                        node.type = "image";
                        node.id = this.obtainSequence();

                        node.url = ele.url || "";
                        nodes.push(node);
                    }
                }
                this.articleObj.nodes = nodes;
                this.trimNodes();
            },
            trimNodes() {
                var list = this.articleObj.nodes;
                var nodes = [];
                var temp = null;
                for (var i = 0; i < list.length; i++) {
                    var node = list[i];
                    if (node.type == "image") {
                        nodes.push(node);
                        temp = null;
                        continue;
                    }
                    if (!temp) {
                        temp = node;
                        nodes.push(temp);
                        continue;
                    }
                    if (node.type == "text") {
                        temp.content += node.content;
                    }
                }
                if (nodes.length == 0 || nodes[nodes.length - 1].type != "text") {
                    var node = {};
                    node.id = this.obtainSequence();
                    node.type = "text";
                    node.content = "";
                    nodes.push(node);
                }
                this.articleObj.nodes = nodes;
            },
            imageLoad(ev, node) {
                // var query = uni.createSelectorQuery().in(this);
                // query.select(".content").boundingClientRect((data) => {
                //     var cw = data.width;
                //     var iw = ev.detail.width;
                //     var ih = ev.detail.height;
                //     node.width = cw + "px";
                //     node.height = ih / iw * cw + "px";
                // }).exec();
            },
            titleChange(ev) {
                this.articleObj.title = ev.detail.value;
            },
            textChange(ev, node) {
                node.content = ev.detail.value;
                setTimeout(() => {
                    node.cursor = 1;
                }, 500)
            },

            textBlur(ev, index) {
                this.selection.index = index;
                this.selection.cursor = ev.detail.cursor;
            },

            obtainSequence() {
                this.sequence++;
                return this.sequence;
            },

            selectImage() {
                uni.chooseImage({
                    count: 1,
                    success: (res) => {
                        var path = res.tempFilePaths[0];
                        // 实际项目中应上传图片到服务一起，获取url后再添加
                        that.addImage(path);
                    }
                })
            },

            addImage(path) {
                that.uploadImage(path, (url)=>{
                    var index = that.selection.index;
                    var cursor = that.selection.cursor;
                    var snode = that.articleObj.nodes[index];
                    var content = snode.content;
                    if (cursor == 0) {} else if (cursor < content.length) {
                        snode.content = content.substring(0, cursor);
                        var node = {};
                        node.id = that.obtainSequence();
                        node.type = "text";
                        node.content = content.substring(cursor);
                        that.articleObj.nodes.splice(index + 1, 0, node);
                        index++;
                    } else {
                        index++;
                    }
                    var node = {};
                    node.id = that.obtainSequence();
                    node.type = "image";
                    node.url = url;
                    node.width = "100px";
                    node.height = "100px";
                    that.articleObj.nodes.splice(index, 0, node);
                    that.trimNodes();
                })
            },

            deleteImage(ev, node, index) {
                uni.showModal({
                    content: '你确定删除吗？',
                    success: (res) => {
                        if (!res.confirm) {
                            return;
                        }
                        this.articleObj.nodes.splice(index, 1);
                        if (this.selection.index > index) {
                            this.selection.index--;
                        }
                        this.trimNodes();
                        var url = node.url;
                        this.$emit("deleteImage", {
                            url: url
                        });
                    }
                });
            },


        }

    }
</script>

<style>
    page {
        background-color: #f3f3f3;
    }
</style>

<style lang="scss">
    .coverImage {
        width: 690rpx;
        height: 280rpx;
        background-color: #ffffff;
        border-radius: 15rpx;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        margin-top: 31rpx;

        .imageWrapper {
            position: relative;

            .image {
                width: 420rpx;
                height: 146rpx;
                border-radius: 10rpx;
            }

            .delete {
                width: 36rpx;
                height: 36rpx;
                background-color: #202020;
                opacity: 0.8;
                position: absolute;
                top: -18rpx;
                right: -18rpx;
                border-radius: 50%;
            }
        }

        .upload {
            width: 420rpx;
            height: 146rpx;
            background-color: #fbfbfb;
            border-radius: 10rpx;
            border: solid 1rpx #e1e1e1;
            font-size: 28rpx;
            color: #999999;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;

            .icon {
                width: 48rpx;
                height: 48rpx;
                margin-bottom: 10rpx;
            }

        }

        .text {
            font-size: 30rpx;
            font-weight: normal;
            font-stretch: normal;
            letter-spacing: 0rpx;
            color: #333333;
            margin-top: 21rpx;
            text-align: center;
        }
    }

    .container {
        margin-top: 30rpx;
        width: 690rpx;
        background-color: #ffffff;
        border-radius: 15rpx;
        padding: 30rpx;
        margin-bottom: 35rpx;

        .title {
            display: flex;
            font-size: 30rpx;
            color: #666666;
            margin-bottom: 33rpx;

            .edit {
                width: 500rpx;
                font-size: 30rpx;
                margin-left: 40rpx;
                color: #121212;
            }
        }

        .line {
            width: 630rpx;
            height: 1px;
            background-color: #e3e3e3;
        }
    }

    .content {
        width: 100%;
        display: flex;
        flex-direction: column;

        // align-items: center;
        .nodes {
            width: 100%;
            min-height: 300rpx;

            .node {
                width: 100%;
                position: relative;
                overflow: hidden;
                margin-bottom: 30rpx;

                .text {
                    width: 100%;
                    font-size: 30rpx;
                    line-height: 35rpx;
                }

                .btn-delete {
                    width: 108rpx;
                    height: 54rpx;
                    background-color: #ffffff;
                    border-radius: 27rpx;
                    border: solid 1rpx #e4e4e4;
                    text-align: center;
                    line-height: 54rpx;
                    color: #fc4849;
                    font-size: 26rpx;
                    position: absolute;
                    top: 50%;
                    left: 50%;
                    transform: translateX(-50%) translateY(-50%);


                }
            }
        }


        .image {
            width: 95%;
            border-radius: 20rpx;
        }



        .addImg {
            width: 150rpx;
            height: 150rpx;
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            font-size: 24rpx;
            line-height: 40rpx;
            background-color: #fbfbfb;
            border-radius: 10rpx;
            border: solid 1rpx #e1e1e1;
            color: #999999;
            margin-top: 50rpx;
        }
    }

    .saveBtn {
        width: 690rpx;
        height: 96rpx;
        background-image: linear-gradient(#16a5fe,
                #16a5fe),
            linear-gradient(90deg,
                #24c9ff 0%,
                #349dee 100%);
        background-blend-mode: normal,
            normal;
        box-shadow: 1rpx 2rpx 14rpx 0rpx rgba(66, 66, 66, 0.41);
        border-radius: 48rpx;
        font-size: 32rpx;
        color: #ffffff;
        line-height: 96rpx;
        text-align: center;
        margin-bottom: 71rpx;
    }


    .popupContainer {
        .wrapper {
            font-size: 32rpx;
            height: 122rpx;
            width: 750rpx;
            line-height: 122rpx;
            text-align: center;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 32rpx;

            .icon {
                width: 44rpx;
                height: 44rpx;
                margin-right: 20rpx;
            }
        }

        .album {
            color: #121212;
        }

        .camera {
            color: #121212;
        }

        .cancel {
            color: #666666;
        }

        .line {
            width: 750rpx;
            height: 1px;
            background-color: #e3e3e3;
        }
    }
</style>
